package cn.wolfcode.postbar.interceptor;


import cn.wolfcode.postbar.annotation.RequiredLogin;
import cn.wolfcode.postbar.domain.UserInfo;
import cn.wolfcode.postbar.redis.service.IUserInfoRedisService;
import cn.wolfcode.postbar.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登陆拦截器
 */
//@Component //方式一
public class CheckLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    //重写登陆拦截方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //解决跨域问题 instance实例 判断这个实例是不是HandlerMethod对象,不是的时候就放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //1判断当前请求映射方法是否贴@RequiredLogin标签
        HandlerMethod hm =(HandlerMethod) handler;
        //2如果有,进行登陆校验
        String token = request.getHeader("token");
        //UserInfo user = userInfoRedisService.getUserByToken(token);
        if (hm.hasMethodAnnotation(RequiredLogin.class)) {
            //2如果有,进行登陆校验
            //String token = request.getHeader("token");
            UserInfo user = userInfoRedisService.getUserByToken(token);
            if (user == null) {
                //返回json格式,没有登陆提示
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;
            }
        }
        //3如果没有放行
        return true;
    }
}
